<template>
  <div>
    <div class="title">{{ isEdit ? "编辑" : "新增" }}满减活动</div>
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="fromRef"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="活动名称" prop="name" width="55">
        <el-input
          v-model="ruleForm.name"
          style="width:473px"
          placeholder="请输入活动名称"
          maxlength="5"
        ></el-input>
        <span class="remark">活动名称不超过5个字</span>
      </el-form-item>
      <el-form-item label="活动时间" prop="useDateValue">
        <el-date-picker
          v-model="ruleForm.useDateValue.startTime"
          type="date"
          placeholder="开始日期"
          style="width:220px"
          :picker-options="pickerOptions"
          :disabled="idDisabled"
        ></el-date-picker>
        <span style="margin-left:10px;color:#ccc">至</span>
        <el-date-picker
          v-model="ruleForm.useDateValue.endTime"
          type="date"
          placeholder="结束日期"
          style="width:220px;margin-left:10px"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="活动规则" prop="actRules">
        <ActRuleAdd ref="actRule" :fullContent="fullContent" />
      </el-form-item>
      <el-form-item label="商品选择" prop="actRules">
        <ApointGoods
          ref="apointComp"
          :actType="actType"
          :content="fullContent"
        />
      </el-form-item>
      <el-form-item label="可用抵扣">
        <el-checkbox label="积分" v-model="ruleForm.deduction"></el-checkbox>
        <span class="remark">仅勾选的抵扣方式，可在下单时间时使用</span>
      </el-form-item>
      <el-form-item label="使用优惠">
        <div style="display:flex">
          <el-checkbox-group v-model="ruleForm.applyType">
            <el-checkbox
              v-for="(item, index) in applyList"
              :label="item"
              :key="index"
              >{{ item }}</el-checkbox
            >
          </el-checkbox-group>
          <span class="remark">买家下单时仅可用与勾选的活动类型同时使用</span>
        </div>
      </el-form-item>
    </el-form>
    <div class="pageButtom">
      <el-button @click="$router.push({ name: 'FullIndex' })">取消</el-button>
      <el-button type="primary" @click="save">保存</el-button>
    </div>
  </div>
</template>

<script lang="ts">
import { Vue, Component, Ref } from "vue-property-decorator";
import ActRuleAdd from "./ActRuleAdd.vue";
import ApointGoods from "../../common/ApointGoods.vue";
import DateUtil from "@/store/modules/date";
import {
  addFull,
  fullActivityDet,
  updateFullActivity,
} from "@/api/fullReduce/fullActive";
Component.registerHooks(["beforeRouteLeave"]);

@Component({
  components: {
    ActRuleAdd,
    ApointGoods,
  },
})
export default class FullReduceAdd extends Vue {
  actType = "FullReduceAdd";

  @Ref()
  readonly fromRef: HTMLFormElement;

  @Ref()
  readonly actRule: HTMLFormElement;

  @Ref()
  readonly apointComp: HTMLFormElement;

  /** 可使用优惠券选项 */
  applyList = ["会员价", "优惠券"];

  ruleForm = {
    name: "",
    useDateValue: {
      startTime: "" as any,
      endTime: "" as any,
    },
    applyType: [],
    deduction: false,
  };

  rules = {
    name: [{ required: true, message: "请输入活动名称", trigger: "blur" }],
    useDateValue: [
      {
        validator: this.validatePass,
        required: true,
        trigger: "blur",
      },
    ],
    actRules: [
      { validator: this.rulevalidate, required: true, trigger: "blur" },
    ],
  };

  pickerOptions = {
    disabledDate(time) {
      const now = new Date(new Date().toLocaleDateString()).getTime();
      return time.getTime() < now;
    },
  };

  rulevalidate() {
    console.log("test");
  }

  validatePass(rule, value, callback) {
    new Date(value.startTime).getTime();
    new Date(new DateUtil("").getYMD(new Date())).getTime();
    if (!value.endTime || !value.startTime) {
      callback(new Error("请输入活动时间"));
    } else {
      if (value.startTime.getTime() > value.endTime.getTime()) {
        callback(new Error("结束时间不能小于开始时间"));
      }
    }
  }

  /** 禁用状态 */
  idDisabled = false;

  /**
   * 编辑时获取的满减详情
   */
  fullContent = {};

  /** 退出弹窗状态 */
  saveFlag = false;

  /** 是否编辑商品 */
  isEdit = false;

  mounted() {
    this.isEdit = this.$route.params.id ? true : false;
    this.$route.meta.title = this.$route.params.id
      ? "编辑满减活动"
      : "新增满减活动";

    if (this.$route.params.id) {
      this.getFullDetail();
    }
  }

  /**
   * 获取满减活动详情
   */
  getFullDetail() {
    fullActivityDet(this.$route.params.id, {}).then(res => {
      const productVos = res.data.discountProductVos;
      const result = res.data.fullScaleVo;
      const disType = result.status === 1 ? true : false;
      this.idDisabled = disType;
      this.ruleForm.name = result.name;
      this.ruleForm.deduction = result.deductionType === "0" ? true : false;
      this.ruleForm.applyType = this.dealUse(result.applyType, 1);
      this.ruleForm.useDateValue.startTime = new Date(result.startTime);
      this.ruleForm.useDateValue.endTime = new Date(result.endTime);
      this.fullContent = { ...result, disType, productVos };
    });
  }

  /**
   * 处理优惠数据
   */
  dealUse(item, type) {
    if (type === 1) {
      item = item
        .replace("0", "会员价")
        .replace("1", "优惠券")
        .split(",");
      return item;
    } else {
      let applyType = item.join(",");
      applyType = applyType.replace("会员价", "0").replace("优惠券", "1");
      return applyType;
    }
  }

  /**
   * 验证表单
   */
  formValid() {
    return this.fromRef.validate();
  }

  /**
   * 保存满减活动
   */
  save() {
    this.formValid();

    const check = this.checkSecond();
    if (!check) {
      return;
    }

    this.apointComp.pointGoodsList.forEach(item => {
      item.productId = item.id;
    });
    const applyType = this.dealUse(this.ruleForm.applyType, 2);
    const parma = {
      applyType,
      deductionType: this.ruleForm.deduction ? 0 : "",
      startTime:
        new DateUtil("").getYMDs(this.ruleForm.useDateValue.startTime) +
        " 00:00:00",
      endTime:
        new DateUtil("").getYMDs(this.ruleForm.useDateValue.endTime) +
        " 23:59:59",
      name: this.ruleForm.name,
      fullScaleProducts: this.apointComp.pointGoodsList,
      fullScaleRules: this.actRule.fullList,
      productType: this.apointComp.goodRadio,
      id: this.$route.params.id ? (this.fullContent as any).id : "",
    };
    if (parma.fullScaleRules[0].ruleType === 0) {
      if (
        Number(parma.fullScaleRules[0].conditionAmount) <
        Number(parma.fullScaleRules[0].discountAmount)
      ) {
        this.$message.error("满减金额不能大于满足条件");
        return;
      }
    }
    if (this.$route.params.id) {
      this.editFull(parma);
      return;
    }
    addFull(parma).then(res => {
      if (res.code === 200) {
        this.saveFlag = true;
        this.$message.success("发布成功");
        this.$router.push({ name: "FullIndex" });
      }
    });
  }

  /**
   * 二次验证条件
   */
  checkSecond() {
    const start = this.ruleForm.useDateValue.startTime.getTime();
    const end = this.ruleForm.useDateValue.endTime.getTime();
    new Date(new DateUtil("").getYMD(new Date())).getTime();
    if (start > end) {
      return false;
    }

    if (!this.actRule.validType) {
      this.$message.error("请输入活动规则");
      return false;
    }
    if (
      this.apointComp.goodRadio !== 0 &&
      this.apointComp.pointGoodsList.length === 0
    ) {
      this.$message.error("请选择指定商品");
      return false;
    }
    return true;
  }

  /**
   * 编辑满减活动
   */
  editFull(param) {
    updateFullActivity(param).then(res => {
      if (res.code === 200) {
        this.$message.success("编辑成功");
        this.saveFlag = true;
        this.$router.push({ name: "FullIndex" });
      }
    });
  }

  beforeRouteLeave(to, from, next) {
    if (this.saveFlag) {
      next();
      return;
    }
    this.$confirm(
      `确定要退出${
        this.$route.params.id ? "编辑" : "发布"
      }满减活动?退出后，未保存的信息将不会保留!`,
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      },
    ).then(() => {
      next();
    });
  }
}
</script>

<style lang="scss" scoped>
.title {
  margin: 10px 0px;
  margin-left: 10px;
  font-weight: bold;
  font-size: 14px;
  margin-bottom: 20px;
}

.remark {
  margin-left: 20px;
  color: #9b9b9b;
}

.pageButtom {
  margin-top: 80px;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
